﻿using Clock.Models;
using Dotnet.Code;
using Dotnet.Code.Extend;
using My.Dotnet.Net;
using System.Net;
using System.Xml.Linq;
using Wutos.Domain;

namespace Clock.Controllers.Api
{
    public partial class StockController
    {
        /// <summary>
        /// 获取单支股票汇总信息
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        private StockSum CaclSingleStockSum(List<StockEntity> list, double price=0, double increase=0)
        {
            if (list == null || list.Count == 0) throw new ArgumentException("参数为空");
            Int64? sum成交数量 = 0;
            StockSum stockSum = new StockSum();
            double? sum成交金额 = 0, sum手续费 = 0, sum印花税 = 0, sum其他杂费 = 0, sum发生金额 = 0;
            try
            {
                foreach (StockEntity item in list)
                {
                    stockSum.name = item.证券名称;
                    stockSum.code = item.证券代码;

                    double? 成交金额 = 0;
                    sum成交数量 += item.成交数量;
                    if (item.操作.Trim() == "股息入账") 成交金额 = item.成交金额?.ToDouble(3);
                    else if (item.操作.Trim() == "股息红利税补缴") 成交金额 = item.成交金额 * (-1);
                    else 成交金额 = (item.成交均价 * item.成交数量 * (-1))?.ToDouble(3);
                    sum成交金额 = (sum成交金额+成交金额)?.ToDouble(4);
                    Console.WriteLine($"成交金额={成交金额}\t\t\tsum成交金额={sum成交金额}");
                    sum手续费 += item.手续费;
                    sum印花税 += item.印花税;
                    sum其他杂费 += item.其他杂费;
                    sum发生金额 += item.发生金额;
                }
                stockSum.cjsl = sum成交数量;
                stockSum.sxf = sum手续费?.ToDouble(3);
                stockSum.yhs = sum印花税?.ToDouble(3);
                stockSum.qtzf = sum其他杂费?.ToDouble(3);
                stockSum.fsje = sum发生金额?.ToDouble(3);
                stockSum.cjje = sum成交金额?.ToDouble(3);
                stockSum.其它费 = (sum手续费 + sum印花税+ sum其他杂费)?.ToDouble(3);
                if (sum成交数量 == 0)
                {
                    stockSum.总 = stockSum.cjje?.ToDouble(3);
                }
                else
                {
                    Models.StockRoot stockRoot = GetNetStockInfo(stockSum.code, stockSum.name);
                    double? avgPrice = GetSingleStockAvgPrice(list);
                    stockSum.均价=avgPrice?.ToDouble(3);
                    stockSum.当前价 = stockRoot.Result.cur.price.ToDouble();
                    stockSum.当前增= stockRoot.Result.cur.increase.ToDouble();
                    stockSum.当日 = (stockRoot.Result.cur.increase.ToDouble() * stockSum.cjsl)?.ToDouble(3);
                    stockSum.持仓 = ((stockRoot.Result.cur.price.ToDouble() - avgPrice) * stockSum.cjsl)?.ToDouble(3);
                    stockSum.总 = (stockSum.当前价 * stockSum.cjsl + stockSum.cjje-stockSum.其它费)?.ToDouble(3);
                }

            }
            catch (Exception)
            {
                stockSum.当日 = increase * stockSum.cjsl;
                stockSum.总 = (price * stockSum.cjsl + stockSum.cjje)?.ToDouble(3);
                stockSum.持仓 = (price - 8.85) * stockSum.cjsl;
            }
            return stockSum;
        }

        private Models.StockRoot GetNetStockInfo(string code,string name="")
        {
            string url = "";
            if (string.IsNullOrEmpty(name))
            {
                url = $"https://finance.pae.baidu.com/vapi/v1/getquotation?group=quotation_minute_ab&code={code}&finClientType=pc";
                //https://finance.pae.baidu.com/vapi/v1/getquotation?code=000759&eprop=min&stock_type=ab&chartType=minute&group=quotation_minute_ab&finClientType=pc

            }
            else
            {
                url = $"https://finance.pae.baidu.com/vapi/v1/getquotation?group=quotation_minute_ab&code={code}&name={name}&finClientType=pc";
            }
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            item.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36";
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            item.Header.Add("Cookie", "PSTM=1715042753; BAIDUID=0AB53CF0247CA5DAD15EEF9520C00AEB:FG=1; BIDUPSID=0C19B7EA4018510F2770C22CCD7606CA; H_WISE_SIDS_BFESS=60853_60980; newlogin=1; BDUSS=WFxcWt-bn5GWVptQnpweXE5ejZaUFhkakQtOFBwMjlZVThURDh2fjhmejdiWUJuSVFBQUFBJCQAAAAAAAAAAAEAAADb0ogINzcwMTE0OTIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPvgWGf74FhnT; BDUSS_BFESS=WFxcWt-bn5GWVptQnpweXE5ejZaUFhkakQtOFBwMjlZVThURDh2fjhmejdiWUJuSVFBQUFBJCQAAAAAAAAAAAEAAADb0ogINzcwMTE0OTIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPvgWGf74FhnT; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BAIDUID_BFESS=0AB53CF0247CA5DAD15EEF9520C00AEB:FG=1; delPer=0; PSINO=3; BA_HECTOR=0h0l85a0akah012h852gahah0r94sj1jnfm221u; ZFY=auRRh:Ab2tW3YGDfk9I2LTzuiHIs1y01QjJ4tWyqNSjw:C; BDRCVFR[oesR6VISAom]=mk3SLVN4HKm; MAWEBCUID=web_JATBADuxMFWuErGhvWnuBRBTXcLiJoLqrnXSJNTZcidhUHSZAb; __bid_n=1942c6de7d284323f60940; H_PS_PSSID=61027_60853_61361_61531_61613_61631_61722; H_WISE_SIDS=61027_60853_61361_61531_61613_61631_61722; BDRCVFR[l9-IMhu-BDf]=mk3SLVN4HKm; ab_sr=1.0.1_NzZlMWE3Njk5NDg3ZjY3MTcwMWI1ZGU0MzYzYjljYWFkZmUyMmZmNjQxNGQyYzg3YTczNTAzYTBhZWFjNTFlM2UxMzA0Mzc5NWQ1M2IwZmI5ZWRjYjJkMzYzMmM3YjUzZjlkYjhlYzNmMDg1MmViMjdjN2Y2MTUwMWYzMDc4YmI4ZjM2OTY0YjRmMzMwOWRiMTQ2ZWMwMThiYTE3MjRkMQ==");
            item.URL = url;
            try
            {
                HttpResult result = http.GetHtml(item);
                if (result != null && result.StatusCode == HttpStatusCode.OK)
                {
                    string html = result.Html;
                    Models.StockRoot stockRoot = Json.ToObject<Models.StockRoot>(html);
                    return stockRoot;
                }
                else
                {
                    throw new Exception(result?.Html);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private double? GetSingleStockAvgPrice(List<StockEntity> list)
        {
            long?  sum数量 = 0;
            double? sum金额 = 0;
            foreach (StockEntity item in list.OrderBy(t=>t.成交日期))
            {
                sum金额 += item.成交均价 * item.成交数量;
                sum数量 += item.成交数量;
                if (sum数量 == 0)
                {
                    sum金额 = 0;
                }
            }
            double? avg= (sum金额/sum数量)?.ToDouble(10);
            return avg;
        }
    }
}
